package UF_NIO;

public class Example {
    public boolean checkMeta(ReadableByteChannel channel) {
        final ByteBuffer b = ByteBuffer.allocate(8);
        try {
            final int i = channel.read(b);
            if (i < 8) {
                return false;
            }
        } catch (IOException e) {
            return false;
        } finally {
            try {
                channel.close();
            } catch (IOException e) {
                // do nothing
            }
        }

        // Cast unsigned character constants prior to comparison
        return (b.get(0) == (byte) 'm' && b.get(1) == (byte) 'y' &&
                b.get(2) == (byte) 'f' && b.get(3) == (byte) 'o' &&
                b.get(4) == (byte) 'r' && b.get(5) == (byte) 'm' &&
                b.get(6) == (byte) 'a' && b.get(7) == (byte) 't');
    }

    public void printOut(final String path) throws IOException {
        final ReadableByteChannel ch = new FileInputStream(path).getChannel();
        if (checkMeta(ch)) {
            try {
                final ByteBuffer b = ByteBuffer.allocate(1024);
                int i;
                while ((i = ch.read(b)) > 0) {
                    print(b);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void print(final ByteBuffer b) {
        while (b.hasRemaining()) {
            System.out.print(b);
        }
        b.clear();
    }
}
